# coding=utf-8
import time
from pyzabbix import ZabbixAPI
from .enums import *
from monitor.settings import zb_username, zb_password, zb_url
from collections import Counter


# 登录zabbix
# zabbix = ZabbixAPI('http://zabbix34-ct.ncfgroup.org/zabbix')
zabbix = ZabbixAPI(zb_url)  # 测试
zabbix.session.verify = False
zabbix.login(zb_username, zb_password)



def group_list():
    return zabbix.hostgroup.get(
        output=['groupid', 'name']
    )


def template_list():
    return zabbix.template.get(output=['name'])


def host_list(group=None):
    if group:
        return zabbix.host.get(
            output=['host', 'hostid', 'name', 'available'],
            groupids=[group],
            selectGroups=['name']
        )
    else:
        return zabbix.host.get(
            output=['host', 'hostid', 'name', 'available'],
            selectGroups=['name']
        )


def get_network(hostid, flow_in, flow_out, card_in, card_out):
    """
    获取一小时网卡流量
    :param hostid: 主机
    :param flow: 流量方向 0-入 1-出
    :param card: 网卡号
    :return:
    """
    ret_li = []
    if all([hostid, flow_in, flow_out, card_in, card_out]):
        key_in = RATE_OF_FLOW.get(int(flow_in))
        key_out = RATE_OF_FLOW.get(int(flow_out))
        if not isinstance(key_in, list):
            key_in = key_in % str(card_in)  # ifHCOutOctets[ethernet1/4]
        if not isinstance(key_out, list):
            key_out = key_out % str(card_out)  # ifHCOutOctets[ethernet1/4]
        item_in = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                               filter={'key_': key_in})
        item_out = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                                  filter={'key_': key_out})

        item_id_in = item_in[0]['itemid']
        item_id_out = item_out[0]['itemid']
        t_till = int(time.time())
        t_from = t_till - 60 * 60

        incoming = zabbix.history.get(
            itemids=[item_id_in],
            history=3,
            output='extend',
            sortfield='clock',
            sortorder='ASC',
            time_from=t_from,
            time_till=t_till
        )

        outgoing = zabbix.history.get(
            itemids=[item_id_out],
            history=3,
            output='extend',
            sortfield='clock',
            sortorder='ASC',
            time_from=t_from,
            time_till=t_till
        )

        ret_li.append({"incoming": incoming, "outgoing": outgoing})
        return ret_li


def get_last_network(hostid, flow_in,flow_out, card_in, card_out):
    """
    获取最新网卡流量
    :param hostid: 主机
    :param flow: 流量方向 0-入 1-出
    :param card: 网卡号
    :return:
    """
    ret_li = []
    if all([hostid, flow_in, flow_out, card_in, card_out]):
        key_in = RATE_OF_FLOW.get(int(flow_in))
        key_out = RATE_OF_FLOW.get(int(flow_out))
        if not isinstance(key_in, list):
            key_in = key_in % str(card_in)
        if not isinstance(key_out, list):
            key_out = key_out % str(card_out)  # ifHCOutOctets[ethernet1/4]
        item_in = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                                  filter={'key_': key_in})
        item_out = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                                   filter={'key_': key_out})

        item_id_in = item_in[0]['itemid']
        item_id_out = item_out[0]['itemid']

        incoming = zabbix.history.get(
            itemids=[item_id_in],
            history=3,
            output='extend',
            sortfield='clock',
            sortorder='DESC',
            limit=1
        )

        outgoing = zabbix.history.get(
            itemids=[item_id_out],
            history=3,
            output='extend',
            sortfield='clock',
            sortorder='DESC',
            limit=1
        )

        ret_li.append({"incoming" : incoming, "outgoing" : outgoing})
        return ret_li


def get_top5_hosts():
    for i in GROUP_li:
        groupid = i['groupid']
        if groupid:
            hosts = zabbix.host.get(
                output=['host'],
                groupids=[groupid],
                selectGroups=['name']
            )

            i.update({"nums" : len(hosts)})
    return GROUP_li


def cpu_list(hostid):
    if hostid:
        item = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                               filter={'key_': 'system.cpu.load[percpu,avg1]'})

        itemid = item[0]['itemid']
        t_till = int(time.time())
        t_from = t_till - 60 * 60

        return zabbix.history.get(
            itemids=[itemid],
            history=0,
            output='extend',
            sortfield='clock',
            sortorder='ASC',
            time_from=t_from,
            time_till=t_till
        )


def cpu_new_list(hostid):
    if hostid:
        item = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                               filter={'key_': 'system.cpu.load[percpu,avg1]'})

        itemid = item[0]['itemid']
        t_till = int(time.time())
        t_from = t_till - 60 * 60

        return zabbix.history.get(
            itemids=[itemid],
            history=0,
            output='extend',
            sortfield='clock',
            sortorder='DESC',
            limit=1
        )


def get_trigger_list():
    triggers = zabbix.trigger.get(only_true=0,
                                  skipDependent=0,
                                  monitored=0,
                                  active=0,
                                  output='extend',
                                  expandDescription=1,
                                  selectHosts=['host'])
    trigger_nums = len(triggers)
    triggers = {"triggers" : trigger_nums}
    return triggers


def memory_list(hostid):
    if hostid:
        item = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                               filter={'key_': 'vm.memory.size[available]'})

        itemid = item[0]['itemid']
        t_till = int(time.time())
        t_from = t_till - 2 * 24 * 60 * 60

        return zabbix.history.get(
            # hostids=[hostid],
            itemids=[itemid],
            history=3,
            output='extend',
            sortfield='clock',
            sortorder='ASC',
            time_from=t_from,
            time_till=t_till
        )


def disk_list(hostid):
    if hostid:
        item = zabbix.item.get(hostids=[hostid], output=["name", "key_", "value_type", "hostid", "status", "state"],
                               filter={'key_': 'vfs.fs.size[/,free]'})

        itemid = item[0]['itemid']
        t_till = int(time.time())
        t_from = t_till - 2 * 24 * 60 * 60

        return zabbix.history.get(
            # hostids=[hostid],
            itemids=[itemid],
            history=3,
            output='extend',
            sortfield='clock',
            sortorder='ASC',
            time_from=t_from,
            time_till=t_till
        )


def event_list():
    t_till = int(time.time())
    t_from = t_till - 7 * 24 * 60 * 60

    triggers = zabbix.trigger.get(
        output=['triggerid', 'description', 'priority']
    )
    triggerDict = {}
    for trigger in triggers:
        triggerDict[trigger['triggerid']] = trigger

    events = zabbix.event.get(
        output='extend',
        selectHosts=['name', 'host'],
        sortfield='clock',
        sortorder='DESC',
        time_from=t_from,
        time_till=t_till,
        limit=100
    )
    event_datas =  [{
        'clock': event['clock'],
        'eventid': event['eventid'],
        'acknowledged': event['acknowledged'],
        'hosts': event['hosts'],
        'trigger': triggerDict.get(event['objectid'])
    } for event in events]

    trigger_hosts = [k["hosts"][0]["host"] for k in event_datas]
    trigger_dict = Counter(trigger_hosts)
    trigger_dict = dict(trigger_dict)
    trigger_dict = dict(sorted(trigger_dict.items(), key=lambda x : x[1], reverse=True)[:5])
    return trigger_dict



def usage(hostid):
    diskItemids = zabbix.item.get(
        hostids=[hostid],
        output=["name",
                "key_",
                "value_type",
                "hostid",
                "status",
                "state"],
        filter={'key_': 'vfs.fs.size[/,pfree]'}
    )
    diskUsage = zabbix.history.get(itemids=[diskItemids[0]['itemid']], history=0, output='extend', sortfield='clock',
                                   sortorder='ASC', limit=1)
    cpuItemids = zabbix.item.get(
        hostids=[hostid],
        output=["name",
                "key_",
                "value_type",
                "hostid",
                "status",
                "state"],
        filter={'key_': 'system.cpu.load[percpu,avg1]'}
    )
    cpuUsage = zabbix.history.get(itemids=[cpuItemids[0]['itemid']], history=0, output='extend', sortfield='clock',
                                  sortorder='ASC', limit=1)

    memoryItemids = zabbix.item.get(
        hostids=[hostid],
        output=["name",
                "key_",
                "value_type",
                "hostid",
                "status",
                "state"],
        filter={'key_': 'vm.memory.size[used]'}
    )
    memoryUsage = zabbix.history.get(itemids=[memoryItemids[0]['itemid']], history=0, output='extend',
                                     sortfield='clock',
                                     sortorder='ASC', limit=1)
    hosts = zabbix.host.get(output=['host', 'hostid', 'name', 'available'], hostids=[hostid], )

    return [{
        'host': hosts[0],
        'diskUsage': diskUsage,
        'cpuUsage': cpuUsage,
        'memoryUsage': memoryUsage,
    }]


def service_history_list(service):
    if service:
        t_till = int(time.time())
        t_from = t_till - 7 * 24 * 60 * 60
        # 所有监控项
        items = zabbix.item.get(
            output=['itemid'],
            filter={'name': service},
            selectHosts=['name', 'host'],
        )
        history = []
        for item in items:
            history.append(
                zabbix.history.get(
                    itemids=[item['itemid']],
                    history=3,
                    output='extend',
                    sortfield='clock',
                    sortorder='ASC',
                    time_from=t_from,
                    time_till=t_till,
                )
            )
        return {
            'items': items,
            'history': history
        }


def service_item_list(service):
    if service:
        # 所有监控项
        items = zabbix.item.get(
            output=['itemid'],
            filter={'name': service},
            selectHosts=['name', 'host'],
        )
        return items


def history_list(itemid):
    if itemid:
        t_till = int(time.time())
        t_from = t_till - 7 * 24 * 60 * 60
        return zabbix.trend.get(
            itemids=[itemid],
            output='extend',
            time_from=t_from,
            time_till=t_till,
        )


def all_usage():
    diskItemids = zabbix.item.get(
        output=["name",
                "key_",
                "value_type",
                "hostid",
                "status",
                "state"],
        filter={'key_': 'vfs.fs.size[/,pfree]'}
    )
    diskUsage = zabbix.history.get(itemids=[diskItemids[0]['itemid']], history=0, output='extend',
                                   sortfield='clock',
                                   sortorder='ASC', limit=1)
    return None


def create_host(group_id, host_name, host_ip, template_id):
    host = zabbix.host.create(
        host=host_name,
        interfaces=[
            {
                'type': 1,
                'main': 1,
                'useip': 1,
                'ip': host_ip,
                'dns': '',
                'port': '10050'
            }
        ],
        groups=[{'groupid': group_id}],
        templates=[
            {
                'templateid': template_id,
            },
        ]
    )
    return host
